#define DBC_CHECK_PRECONDITION

using System;
using System.Xml;

using DesignByContract;

using Outcoding.GraphGenerator.Entities;

namespace Outcoding.GraphGenerator.XmlBuilders {
    public class DatatableXmlBuilder : IXmlBuilder {

        private Datatable mResultObject = null;

        public object ResultObject {
            get {
                return mResultObject;
            }
        }

        public DatatableXmlBuilder(XmlNode datatableXmlNode) {
            Check.Require(datatableXmlNode != null, "Xml source node cannot be null");
            Check.Require(datatableXmlNode.Name.CompareTo(XmlTagNames.datatable.ToString()) == 0, "A Datatable Xml node must be supplied.");
            this.BuildObject(datatableXmlNode);
        }

        private void BuildObject(XmlNode datatableXmlNode) {
            mResultObject = new Datatable();
            try {
                if (datatableXmlNode.Attributes["visible"] != null)
                    mResultObject.IsVisible = ParseIsVisibleAttribute(datatableXmlNode);
                if (datatableXmlNode.Attributes["show-legendkey"] != null)
                    mResultObject.IsLegendKeyVisible = ParseLegendKeyttribute(datatableXmlNode);
            } catch (DesignByContract.PreconditionException preExc) {
                //log error
                mResultObject = null;
                throw;
            }
        }

        private bool ParseIsVisibleAttribute(XmlNode datatableXmlNode) {
            Check.Require(datatableXmlNode.Attributes["visible"] != null, "visible attribute not present");
            return Boolean.Parse(datatableXmlNode.Attributes["visible"].Value);
        }

        private bool ParseLegendKeyttribute(XmlNode datatableXmlNode) {
            Check.Require(datatableXmlNode.Attributes["show-legendkey"] != null, "show-legendkey attribute not present");
            return Boolean.Parse(datatableXmlNode.Attributes["show-legendkey"].Value);
        }
    }
}
